package org.hdax.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.hdax.entity.Permission;
import org.hdax.entity.Role;
import org.hdax.entity.RolePermission;
import org.hdax.service.PermissionService;
import org.hdax.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getAll(){
        Map<String,Object> map = new HashMap<String, Object>();
        List<Permission> permissions = permissionService.getAll();
        map.put("permissions",permissions);
        return map;
    }

    @RequestMapping(value = "/batchUpdate",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> batchUpdate(@RequestParam("str")String str){
        Map<String,Object> map = new HashMap<String, Object>();
        //{}
        JSONObject object = JSON.parseObject(str);
        int role_id = Integer.parseInt(object.get("role_id").toString());
        //删除当前角色所拥有的权限
        rolePermissionService.deleteByRoleId(role_id);
        JSONArray array = object.getJSONArray("ids");
        for(int i = 0;i<array.size();i++){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRole(new Role(role_id));
            rolePermission.setPermission(new Permission(Integer.parseInt(array.get(i).toString())));
            rolePermissionService.saveEntity(rolePermission);
        }
        map.put("result",true);
        return map;
    }
}
